##############################################
##############################################
###Syn. Controls -- Added Matching Criteria###
##############################################
##############################################
library(Synth)
library(doBy)
library(foreign)
library(dplyr)
library(stargazer)
###Import data
#Set working library
setwd("~/OneDrive - Indiana University/FromGoogle/AfroGrid/Ghana/Code_6_4_25/data/")
#Read dataset
ghana.dat.s <- read.csv("ghandatsc.csv")

set.seed(123)
###Set up the treatment province as a numeric indicator
#Indicator
ghana.dat.s$did <- 1
#Collapse by province
sub <- summaryBy(did~STATE_PROVINCE, data=ghana.dat.s, FUN=c("sum"), keep.names =T)
#Rename ID
sub$did <- 1:length(sub$did)
ghana.dat.s$did <- NULL
#Remerge
ghana.dat.s <- left_join(ghana.dat.s, sub)
unique(ghana.dat.s$did)

#Set control districts
control <- ghana.dat.s$did[ghana.dat.s$did!=5]

#Now convert everything to framework for the SC method
ghana.1 <- dataprep(
  foo = ghana.dat.s,
  predictors = c("population","bdist3","NL_sum","p_avg","t_c_avg","acled_battle_state"), 
  predictors.op = "mean",
  time.predictors.prior = 2003:2015,
  dependent = "acled_mil_tot",
  unit.variable = "did",
  time.variable = "year",
  treatment.identifier =5,  
  controls.identifier = unique(control),  
  time.optimize.ssr = 2003:2015,
  time.plot = 2003:2020)

##What do the controls look like
ghana.1$X1

##Averaged values
ghana.1$Z1

#Synth controls
synth.out.s <- synth(data.prep.obj = ghana.1, method = "BFGS")

#Export to tables
synth.tables.s <- synth.tab(dataprep.res = ghana.1, synth.res = synth.out.s)
#Predicted values
synth.tables.s$tab.pred
#Tables of weights
synth.tables.s$tab.w

#Plot the variations
setwd("~/OneDrive - Indiana University/FromGoogle/AfroGrid/Ghana/Code_6_4_25/plots/")
jpeg("figurea1.jpeg", width = 6, height = 6, units = 'in', res = 500)
path.plot(synth.res = synth.out.s, dataprep.res = ghana.1,
          Ylab = "Social conflict rates", Xlab = "Year",
          #    Ylim = c(-0.1, 1), 
          abline(v = 2015, lwd = 3, lty = 2),
          Legend = c("Northern", "Synthetic Northern"), Legend.position = "topright")

dev.off()
